package com.android.fragmentdemo.thread8

import org.junit.Test
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.ReentrantLock

class Demo8 {
    @Test
    fun testRunnable() {
        val reentrantLock = ReentrantLock()
        for (i in 0.until(2)) {
            Thread {
                var condition = true
                try {
                    if (reentrantLock.tryLock(5, TimeUnit.SECONDS)) {
                       timeoutApi()
                    } else {
                        println("executed failed!")
                        condition = false
                    }
                } catch (ex: InterruptedException) {
                    ex.printStackTrace()
                } finally {
                    if (condition) {
                        println("try finally")
                        reentrantLock.unlock()
                    }
                }
            }.start()
        }

        Thread.sleep(15 * 1000)
    }

    private fun timeoutApi() {
        Thread.sleep(8 * 1000)
        println("took 60 ms")
    }
}